package com.woniuxy.cloud.carl.carlgoods.app.apiImpl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.cloud.carl.car.client.CarQueryClient;
import com.woniuxy.cloud.carl.car.client.result.CarForStationDto;
import com.woniuxy.cloud.carl.carlgoods.client.CarSkuClient;
import com.woniuxy.cloud.carl.carlgoods.client.dto.CarSkuDto;
import com.woniuxy.cloud.carl.carlgoods.client.param.AddCarSkuParam;
import com.woniuxy.cloud.carl.carlgoods.infra.mapper.CarSkuMapper;
import com.woniuxy.cloud.carl.carlgoods.infra.mapper.SkuMapper;
import com.woniuxy.cloud.carl.carlgoods.infra.model.CarSku;
import com.woniuxy.cloud.carl.carlgoods.infra.model.Sku;
import com.woniuxy.result.Result;
import com.woniuxy.utils.Assert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
@Slf4j
public class CarSkuImpl implements CarSkuClient {

    @Resource
    private SkuMapper skuMapper;
    @Resource
    private CarQueryClient carQueryClient;
    @Resource
    private CarSkuMapper carSkuMapper;
    @Override
    public Result addCarSku(AddCarSkuParam param) {
        Result<CarForStationDto> result = carQueryClient.getDetail(param.getCarId());
        CarForStationDto car = result.getData();
        Assert.state(car!=null,"该车辆不存在，无法绑定");
        Sku sku = skuMapper.selectById(param.getSkuId());
        Assert.state(sku!=null,"该商品不存在，无法绑定");
        CarSku carSku = BeanUtil.toBean(param, CarSku.class);
        carSku.setRecommandFlag(1);
        carSkuMapper.insert(carSku);
        return Result.success();
    }

    @Override
    public Result<List<CarSkuDto>>findSkuByCarId(Long carId) {
        Result<CarForStationDto> result = carQueryClient.getDetail(carId);
        CarForStationDto car = result.getData();
        Assert.state(car!=null,"该车辆不存在，无法绑定");
        String carName = car.getCarDesc();
        QueryWrapper<CarSku> queryWrapper = new QueryWrapper<CarSku>().eq("car_id", carId);
        List<CarSku> carSkus = carSkuMapper.selectList(queryWrapper);
        List<CarSkuDto> carSkuDtos = BeanUtil.copyToList(carSkus, CarSkuDto.class);
        for (CarSkuDto carSkuDto : carSkuDtos) {
            carSkuDto.setCarName(carName);
            String skuName = skuMapper.selectById(carSkuDto.getSkuId()).getSkuName();
            carSkuDto.setSkuName(skuName);
        }
        return Result.success(carSkuDtos);
    }
}
